//
//  SubscribeNewsListViewController.m
//  suRead
//
//  Created by lidi on 2018/11/30.
//  Copyright © 2018 bao. All rights reserved.
//

#import "SubscribeNewsListViewController.h"
#import "M_Subscribe.h"
#import "Masonry.h"
#import "UIViewController+HUD.h"
#import "UIControl+Blocks.h"
#import "MJRefresh.h"
#import "ServiceSubscribe.h"
#import "ServiceNews.h"
#import "M_News.h"
#import "AccountManager.h"
#import "SubscribeNewsCell.h"
#import "UIViewController+EmptyDataSet.h"
#import "UIImageView+WebCache.h"
#import "M_SubscribeInfo.h"
#import "SubscribeInfoViewController.h"
#import "SubscribeNewsDetailViewController.h"
#import "NewCellManager.h"

@interface SubscribeNewsListViewController ()<UITableViewDataSource,UITableViewDelegate,UIGestureRecognizerDelegate>
@property (nonatomic,strong)UIButton *buttonSubscribe;
@property (nonatomic,strong)UIImageView *iconv;
@property (nonatomic,strong)UITableView *infoTableView;
@property (nonatomic,strong)NSMutableArray *infoDataArray;
@property (nonatomic,strong)NSURLSessionDataTask *requestHandle;
@property (nonatomic,assign)NSInteger currentPageIndex;

@property (nonatomic,strong)M_SubscribeInfo *info;

@property (nonatomic,strong)UIImageView *imageViewIcon;
@property (nonatomic,strong)UILabel *labelName;
@property (nonatomic,strong)UILabel *labelCount;
@end

@implementation SubscribeNewsListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationController.navigationBarHidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    // enable slide-back
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = YES;
        self.navigationController.interactivePopGestureRecognizer.delegate = self;
    }
    
    
    __weak typeof(self) weak_self = self;
    
    //头部导航栏
    UIView *navigationBarView = [UIView new];
    navigationBarView.backgroundColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    [self.view addSubview:navigationBarView];
    [navigationBarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(navigationBarView.superview);
        if (iPhoneX) {
            make.height.equalTo(@88.0f);
        } else {
            make.height.equalTo(@64.0f);
        }
    }];
    
    UIView *titleViewContainer = [UIView new];
    [navigationBarView addSubview:titleViewContainer];
    [titleViewContainer mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(titleViewContainer.superview);
        make.height.equalTo(@44.0f);
    }];
    
    //返回
    UIButton *buttonBack = [UIButton buttonWithType:UIButtonTypeCustom];
    buttonBack.tintColor = [UIColor whiteColor];
    [buttonBack setImage:[[UIImage imageNamed:@"button_backward"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] forState:UIControlStateNormal];
    [titleViewContainer addSubview:buttonBack];
    [buttonBack addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        [weak_self.navigationController popViewControllerAnimated:YES];
    }];
    [buttonBack mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(buttonBack.superview).offset(15.0);
        make.top.bottom.equalTo(buttonBack.superview);
        make.width.equalTo(@44.0f);
    }];
    
    //订阅号信息
    UIView *header = [UIView new];
    UIGestureRecognizer *ges = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(gotoInfoAction:)];
    [header addGestureRecognizer:ges];
    header.userInteractionEnabled = YES;
    header.backgroundColor = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    [self.view addSubview:header];
    [header mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(header.superview);
        make.top.equalTo(navigationBarView.mas_bottom);
        make.height.equalTo(@80.0f);
    }];
    
    self.imageViewIcon = [UIImageView new];
    self.imageViewIcon.layer.cornerRadius = 20.0f;
    self.imageViewIcon.layer.masksToBounds = true;
    [header addSubview:self.imageViewIcon];
    [self.imageViewIcon mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(40, 40));
        make.left.equalTo(self.imageViewIcon.superview).offset(15.0f);
        make.centerY.equalTo(self.imageViewIcon.superview);
    }];
    
    self.labelName = [UILabel new];
    self.labelName.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:17.0f];
    self.labelName.textColor = [UIColor whiteColor];
    [header addSubview:self.labelName];
    [self.labelName mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageViewIcon.mas_right).offset(15.0f);
        make.top.equalTo(self.labelName.superview).offset(20.0f);
    }];
    
    self.iconv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"icon_v"]];
    self.iconv.hidden = YES;
    [header addSubview:self.iconv];
    [self.iconv mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.labelName.mas_right).offset(10.0);
        make.size.mas_equalTo(CGSizeMake(15, 15));
        make.centerY.mas_equalTo(self.labelName.mas_centerY);
    }];
    
    self.labelCount = [UILabel new];
    self.labelCount.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:11.0f];
    self.labelCount.textColor = [UIColor whiteColor];
    [header addSubview:self.labelCount];
    [self.labelCount mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.imageViewIcon.mas_right).offset(15.0f);
        make.top.equalTo(self.labelName.mas_bottom).offset(5.0f);
    }];
    
    self.buttonSubscribe = [UIButton buttonWithType:UIButtonTypeCustom];
    self.buttonSubscribe.layer.cornerRadius = 5.0f;
    self.buttonSubscribe.layer.masksToBounds = true;
    self.buttonSubscribe.titleLabel.font = [UIFont fontWithName:@"FZBIAOYSJW--GB1-0" size:15.0f];
    [header addSubview:self.buttonSubscribe];
    [self.buttonSubscribe mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.buttonSubscribe.superview).offset(-15.0);
        make.size.mas_equalTo(CGSizeMake(50, 25));
        make.centerY.equalTo(self.buttonSubscribe.superview);
    }];
    [self refreshSubscribe];
    [self.buttonSubscribe addActionForControlEvents:UIControlEventTouchUpInside usingBlock:^(UIControl *sender, UIEvent *event) {
        if ([AccountManager sharedAccountManager].f_isLogined) {
            NSString *uid = [AccountManager sharedAccountManager].f_uid;
            if (!weak_self.sub.f_is_subscribe) {
                [ServiceSubscribe doServiceSubscribe:weak_self.sub.f_wid userid:uid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                    [weak_self showHUDText:message];
                    weak_self.sub.f_is_subscribe = YES;
                    [weak_self refreshSubscribe];
                } failure:^(NSString * _Nonnull message) {
                    [weak_self showHUDText:message];
                }];
            } else {
                [ServiceSubscribe doServiceUnsubscribe:weak_self.sub.f_wid userid:uid success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
                    [weak_self showHUDText:message];
                    weak_self.sub.f_is_subscribe = NO;
                    [weak_self refreshSubscribe];
                } failure:^(NSString * _Nonnull message) {
                    [weak_self showHUDText:message];
                }];
            }
        } else {
            //需要登录
            UIStoryboard *personalCenterStoryBoard = [UIStoryboard storyboardWithName:@"PersonalCenter" bundle:[NSBundle mainBundle]];
            UIViewController *controller = [personalCenterStoryBoard instantiateViewControllerWithIdentifier:@"LoginViewController"];
            controller.hidesBottomBarWhenPushed = YES;
            [weak_self showViewController:controller sender:nil];
        }
    }];
    
    self.infoTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.infoTableView.dataSource = self;
    self.infoTableView.delegate = self;
    [self.view addSubview:self.infoTableView];
    [self.infoTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.infoTableView.superview);
        make.top.equalTo(header.mas_bottom);
        if (@available(iOS 11.0, *)) {
            make.bottom.equalTo(self.infoTableView.superview.mas_safeAreaLayoutGuideBottom);
        } else {
            make.bottom.equalTo(self.infoTableView.superview);
        }
    }];
    self.infoTableView.tableFooterView = [UIView new];
    self.infoTableView.backgroundColor = [UIColor whiteColor];
    self.infoTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.infoTableView registerNib:[UINib nibWithNibName:@"SubscribeNewsCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"SubscribeNewsCell"];

    self.infoTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //刷新数据
        [weak_self refreshDatas];
    }];
    
    [self.infoTableView.mj_header beginRefreshing];
}

- (void)refreshSubscribe {
    
    [self.imageViewIcon sd_setImageWithURL:[NSURL URLWithString:self.info.f_service_img] placeholderImage:nil];
    self.labelName.text = self.info.f_service_name;
    self.labelCount.text = [NSString stringWithFormat:@"文章%@篇",self.info.f_service_count];
    
    UIColor *red = [[UIColor alloc] initWithRed:190.0f / 255.0f green:30.0f / 255.0f blue:30.0f / 255.0f alpha:1];
    self.buttonSubscribe.backgroundColor = [UIColor whiteColor];
    if (self.sub.f_is_subscribe) {
        //已订阅
        [self.buttonSubscribe setTitle:@"已订阅" forState:UIControlStateNormal];
        [self.buttonSubscribe setTitleColor:red forState:UIControlStateNormal];
    } else {
        //未订阅
        [self.buttonSubscribe setTitle:@"订阅" forState:UIControlStateNormal];
        [self.buttonSubscribe setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    }
    
    if ([self.info.f_service_cert isEqualToString:@"1"]) {
        self.iconv.hidden = NO;
    } else {
        self.iconv.hidden = YES;
    }
}

- (void)gotoInfoAction:(id)sender {
    SubscribeInfoViewController *controller = [SubscribeInfoViewController new];
    self.info.f_is_subscribe = self.sub.f_is_subscribe;
    controller.info = self.info;
    [self showViewController:controller sender:nil];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    return YES;
}

- (void)refreshDatas
{
    [self emptyDataSetClearAllNotice];
    [self.infoTableView.mj_footer resetNoMoreData];
    
    self.currentPageIndex = 1;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServiceWidList:self.sub.f_wid userid:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_header endRefreshing];
        weak_self.infoDataArray = [NSMutableArray array];
        NSArray *list = [responseObject objectForKey:@"item"];
        if (!list || [list count] == 0) {
            [weak_self emptyDataSetShowEmptyData:@"该服务号还没有发布文章哦"];
            weak_self.infoTableView.mj_footer = nil;
        } else {
            weak_self.infoTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
                [weak_self loadMore];
            }];
        }
        [weak_self.infoDataArray addObjectsFromArray:list];
        [weak_self.infoTableView reloadData];
        weak_self.info = [responseObject objectForKey:@"info"];
        [weak_self refreshSubscribe];
    } failure:^(NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_header endRefreshing];
        [weak_self showHUDText:message];
        //重连
        if (!weak_self.infoDataArray || ![weak_self.infoDataArray count]) {
            [weak_self emptyDataSetShowNetWorkAvaliable:^{
                [weak_self.infoTableView.mj_header beginRefreshing];
            }];
        }
    }];
}

- (void)loadMore
{
    self.currentPageIndex ++;
    if (self.requestHandle) {
        [self.requestHandle cancel];
        self.requestHandle = nil;
    }
    
    __weak typeof(self) weak_self = self;
    NSString *uid = [AccountManager sharedAccountManager].f_uid;
    if (![AccountManager sharedAccountManager].f_isLogined) {
        uid = @"";
    }
    [ServiceSubscribe doFetchServiceWidList:self.sub.f_wid userid:uid pageindex:self.currentPageIndex pagesize:DEFAULT_PAGE_SIZE success:^(id  _Nonnull responseObject, NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_footer endRefreshing];
        NSArray *list = [responseObject objectForKey:@"item"];
        if (list && [list isKindOfClass:[NSArray class]] && [list count] > 0) {
            [weak_self.infoDataArray addObjectsFromArray:list];
        } else {
            [weak_self.infoTableView.mj_footer endRefreshingWithNoMoreData];
        }
        [weak_self.infoTableView reloadData];
    } failure:^(NSString * _Nonnull message) {
        [weak_self.infoTableView.mj_footer endRefreshing];
        [weak_self showHUDText:message];
    }];
}

#pragma mark tableViewDatasouce Delegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.infoDataArray count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_News *news = [self.infoDataArray objectAtIndex:indexPath.row];
    SubscribeNewsCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SubscribeNewsCell"];
    cell.newsData = news;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    M_News *news_ = [self.infoDataArray objectAtIndex:indexPath.row];
    SubscribeNewsDetailViewController *controller = [SubscribeNewsDetailViewController new];
    
    NSString *uid = @"";
    if ([AccountManager sharedAccountManager].f_isLogined) {
        uid = [AccountManager sharedAccountManager].f_uid;
    }
    controller.urlString = [NSString stringWithFormat:@"%@&aid=%@&userid=%@&type=%@&wid=%@",url_service_wid_info,news_.f_id,uid,news_.f_type,news_.f_wid];
    controller.f_thumbnail = news_.f_thumbnail;
    controller.hidesBottomBarWhenPushed = YES;
    [self showViewController:controller sender:nil];
    
    //增加浏览量
    [ServiceNews doSendRead:news_.f_id success:nil failure:nil];
    
    //保存阅读记录
    [[NewCellManager shared] saveReadHistory:news_.f_id];
    [tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
}

@end
